import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


public class Leetcode599 {

    public String[] findRestaurant(String[] list1, String[] list2) {
        if (list1.length > list2.length) {
            return findRestaurant(list2, list1);
        }

        Map<String, Integer> count = new HashMap<>(list1.length);
        for (int i = 0; i < list1.length; i++) {
            count.put(list1[i], i);
        }

        List<String> res = new ArrayList<>();
        int min = Integer.MAX_VALUE;
        for (int i = 0; i < list2.length; i++) {
            if (i > min) {
                break;
            }

            if (count.containsKey(list2[i])) {
                int currentSumIndex = count.get(list2[i]) + i;
                if (currentSumIndex < min) {
                    res.clear();
                    res.add(list2[i]);
                    min = currentSumIndex;
                } else if (currentSumIndex == min) {
                    res.add(list2[i]);
                }
            }
        }

        return res.toArray(new String[0]);
    }
}
